/**
 * This file is part of iSecurePasswords.
 *
 *   iSecurePasswords is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   iSecurePasswords is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with iSecurePasswords.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * Author: Matthew MacGregor
 * Created: 2012
 * iSecurePasswords, copyright 2013 Sudolink, LLC
 * 
 */ 
package com.sudolink.isp.ui;

import com.matsuzine.utils.HelperMethods;
import com.sudolink.crypto.CryptoException;
import com.sudolink.cryptodata.CryptInfoBundle;
import com.sudolink.cryptodata.SecureDataManager;
import com.sudolink.io.IStore;
import com.sudolink.io.Store;
import com.sudolink.isp.app.Application;
import java.awt.Component;
import java.io.IOException;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author dev
 */
public class PasswordChanger extends javax.swing.JFrame {

    private IRefreshData iRefresh;

    /**
     * Creates new form PasswordChanger
     */
    public PasswordChanger(Component parent, IRefreshData iRefresh) {
        initComponents();
        this.iRefresh = iRefresh;
        this.setLocationRelativeTo(parent);
        Application.refreshLastUserInteractionTime();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        pwOldPassword = new javax.swing.JPasswordField();
        lOldPassword = new javax.swing.JLabel();
        lNewPassword = new javax.swing.JLabel();
        pwNewPassword = new javax.swing.JPasswordField();
        pwRepeatPassword = new javax.swing.JPasswordField();
        lRepeatPassword = new javax.swing.JLabel();
        btnApply = new javax.swing.JButton();
        lInfo = new javax.swing.JLabel();

        lOldPassword.setText("Old Password");

        lNewPassword.setText("New Password");

        lRepeatPassword.setText("Repeat Password");

        btnApply.setText("Apply");
        btnApply.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnApplyActionPerformed(evt);
            }
        });

        lInfo.setForeground(new java.awt.Color(102, 102, 102));
        lInfo.setText("***Be sure to remember your new master password!***");
        lInfo.addContainerListener(new java.awt.event.ContainerAdapter() {
            public void componentAdded(java.awt.event.ContainerEvent evt) {
                lInfoComponentAdded(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lNewPassword)
                            .addComponent(lOldPassword)
                            .addComponent(lRepeatPassword))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(pwRepeatPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 263, Short.MAX_VALUE)
                            .addComponent(pwOldPassword)
                            .addComponent(pwNewPassword)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(lInfo, javax.swing.GroupLayout.DEFAULT_SIZE, 377, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnApply)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(pwOldPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lOldPassword))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lNewPassword)
                    .addComponent(pwNewPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lRepeatPassword)
                    .addComponent(pwRepeatPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(10, 10, 10)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lInfo, javax.swing.GroupLayout.DEFAULT_SIZE, 38, Short.MAX_VALUE)
                    .addComponent(btnApply))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void lInfoComponentAdded(java.awt.event.ContainerEvent evt) {//GEN-FIRST:event_lInfoComponentAdded
        
    }//GEN-LAST:event_lInfoComponentAdded

    private void btnApplyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnApplyActionPerformed

        CryptInfoBundle bundle = Application.getPrivateKeys();
        byte[] oldPassword = HelperMethods.convertCharArrayToByteArray(pwOldPassword.getPassword());

        if (Arrays.equals(oldPassword, bundle.getPassword())) {

            //TODO: Add some validation logic here
            boolean isValidPassword = true;

            if (isValidPassword) {
                if (Arrays.equals(pwNewPassword.getPassword(), pwRepeatPassword.getPassword())) {
                    
                    SecureDataManager mgr = Application.getSecureDataManager();
                    mgr.decryptEach(bundle);
                    //Set up the new bundle keys
                    CryptInfoBundle bundle2 = new CryptInfoBundle();
                    bundle2.setPassword(HelperMethods.convertCharArrayToByteArray(pwNewPassword.getPassword()));
                    bundle2.setSalt(HelperMethods.generateSalt());                   
                    Application.setPrivateKeys(bundle2);
                    mgr.encryptEach(bundle2);
                    
                    try {
                        IStore store = new Store( Application.getPathToDatabase() );
                        store.shouldOverwrite(true);
                        mgr.saveAll(store, bundle2);
                        Application.setPrivateKeys(bundle2);
                    } catch (CryptoException | IOException ex) {
                        Logger.getLogger(PasswordChanger.class.getName()).log(Level.SEVERE, null, ex);
                    } 
                    this.dispose();
                } else {
                    JOptionPane.showMessageDialog(this, "The new passwords don't match. Try again.");
                }
            }
        } else {
            JOptionPane.showMessageDialog(this, "The old password isn't correct. Try again.");
        }



    }//GEN-LAST:event_btnApplyActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnApply;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel lInfo;
    private javax.swing.JLabel lNewPassword;
    private javax.swing.JLabel lOldPassword;
    private javax.swing.JLabel lRepeatPassword;
    private javax.swing.JPasswordField pwNewPassword;
    private javax.swing.JPasswordField pwOldPassword;
    private javax.swing.JPasswordField pwRepeatPassword;
    // End of variables declaration//GEN-END:variables
}
